package model

type DrawCardServer interface {
	Create(*DrawCard) (err error)
	GetCountDay(string, int) int
	Check(string) int
	GetSumAllTime(int) (int, error)
	GetSumDayTime(string, int) (sum int, err error)
}

type drawCardServer struct {
}

func NewDrawCardServer() DrawCardServer {
	return &drawCardServer{}
}

func (u *drawCardServer) Create(draw *DrawCard) (err error) {
	sql := "INSERT INTO draw_card (open_id, money, create_time, created_day, sign, name) VALUES (?, ?, ?, ?, ?, ?)"
	stmt, err := Db.Prepare(sql)
	if err != nil {
		return
	}
	defer stmt.Close()

	res, err := stmt.Exec(draw.OpenId, draw.Money, draw.CreateTime, draw.CreatedDay, draw.Sign, draw.Name)
	if err != nil {
		return
	}
	id, err := res.LastInsertId()
	if err != nil {
		return
	}
	draw.Id = int(id)
	return nil
}

func (u *drawCardServer) GetCountDay(openId string, createdAt int) (count int) {
	_ = Db.QueryRow("SELECT count(id) FROM draw_card WHERE created_day = ? AND open_id = ?", createdAt, openId).Scan(&count)
	return
}

func (u *drawCardServer) Check(openId string) (count int) {
	_ = Db.QueryRow("SELECT count(id) FROM draw_card WHERE types = 1 AND open_id = ?", openId).Scan(&count)
	return
}

func (u *drawCardServer) GetSumAllTime(createdAt int) (sum int, err error) {
	err = Db.QueryRow("SELECT sum(money) FROM draw_card WHERE created_day = ?", createdAt).Scan(&sum)
	return
}

func (u *drawCardServer) GetSumDayTime(openId string, createdAt int) (sum int, err error) {
	err = Db.QueryRow("SELECT sum(money) FROM draw_card WHERE created_day = ? AND open_id = ?", createdAt, openId).Scan(&sum)
	return
}
